package com.link2room.blaster.util;

import com.link2room.common.exception.SysException;
import com.link2room.common.redis.RedisUtil;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.MD5Util;
import com.link2room.common.util.StringUtil;
import com.link2room.blaster.entity.DayuOption;
import com.link2room.blaster.entity.MsgTemplate;
import com.link2room.enums.exception.BlasterSysExceptionEnum;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by LN on 2017/4/18.
 */
@Component("SMSUtil")
public class SMSUtil {
    @Resource
    private ICommonService commonServiceSupport;
    @Resource
    private RedisUtil redisUtil;

    public DayuOption selectDayuOptionBylhotelCode(String lhotelGroupCode) throws Exception {
        //查找出大于配置
        DayuOption dayuOpt = new DayuOption();
        dayuOpt.setLhotelGroupCode(lhotelGroupCode);
        DayuOption dy = commonServiceSupport.findOneEQ(DayuOption.class, dayuOpt);
        if(dy==null){
            throw new SysException(BlasterSysExceptionEnum.NO_DAYU_OPT.getCode(), BlasterSysExceptionEnum.NO_DAYU_OPT.getMsg()+"lhotelGroupCode:"+lhotelGroupCode, BlasterSysExceptionEnum.NO_DAYU_OPT.getBizType());
        }
        return dy;
    }


    /**
     * 电话号码判断
     * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
     *联通：130、131、132、152、155、156、185、186
     *电信：133、153、180、189、（1349卫通）
     * @param telNum
     * @return
     */
    public boolean isMobiPhoneNum(String telNum){
        String regex = "^(1[34578])\\d{9}$";
        Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(telNum);
        return m.matches();
    }

    /**
     * 生成6位数字验证码
     * @return
     */
    public String randomCode_6(){
        Random random = new Random();
        String result="";
        for(int i=0;i<6;i++) {
            result += random.nextInt(10);
        }
        return result;
    }

    /**
     * 缓存验证码，生成msgId并返回，返回给用户用于验证
     * msgId 根据手机号码和集团md5生成，每次缓存会把原来的缓存覆盖
     * @param verificationCode
     * @return
     */
    public String cacheVerificationCode(String verificationCode,String templateCode,String phone,String hotelGroupCode){

        String msg = getMsgId(phone,hotelGroupCode,templateCode);
        //1天有效
        redisUtil.set(msg,verificationCode,86400L);
        return msg;
    }

    public String getMsgId(String phone,String hotelGroupCode,String templateCode){

        return "msgId-"+ MD5Util.getMd5(phone+hotelGroupCode+templateCode) ;
    }

    /**
     * 发送短信
     * @param signName
     * @param lhotelGroupCode
     * @param smsParamString
     * @param template
     * @param mobile
     * @throws Exception
     */
    public void sendMsg(String signName , String lhotelGroupCode, String smsParamString, MsgTemplate template, String mobile) throws Exception {

        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName(signName);//短信签名
        req.setSmsParamString(smsParamString);
        req.setRecNum(mobile);
        req.setSmsTemplateCode(template.getTemplateId());

        TaobaoClient client = initClient(lhotelGroupCode);

        AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
        if(StringUtil.isNotBlank(rsp.getErrorCode())){
            throw new SysException(BlasterSysExceptionEnum.DAYU_SDK_ERROR.getCode(), BlasterSysExceptionEnum.DAYU_SDK_ERROR.getMsg()+rsp.getBody(), BlasterSysExceptionEnum.DAYU_SDK_ERROR.getBizType());
        }

    }

    private TaobaoClient initClient(String lhotelGroupCode) throws Exception {
        DayuOption dy = selectDayuOptionBylhotelCode(lhotelGroupCode);
        String appkey = dy.getAppkey();
        String secret = dy.getSecret();
        String url = dy.getUrl();
        return new DefaultTaobaoClient(url, appkey, secret);
    }

    /**
     * 验证码校验
     * @param msgId
     * @param verificationCode
     */
    public void verifyCode(String msgId,String verificationCode,long timeoutSecond){
        if(!redisUtil.exists(msgId)){
            throw new SysException(BlasterSysExceptionEnum.VERIFICATIONCODE_OVERDUE.getCode(),
                    BlasterSysExceptionEnum.VERIFICATIONCODE_OVERDUE.getMsg()+"msgId:"+msgId,
                    BlasterSysExceptionEnum.VERIFICATIONCODE_OVERDUE.getBizType());
        }else{
            String cacheCode = (String) redisUtil.get(msgId);
            if(!cacheCode.equals(verificationCode)){
                throw new SysException(BlasterSysExceptionEnum.VERIFICATIONCODE_ERROR.getCode(),
                        BlasterSysExceptionEnum.VERIFICATIONCODE_ERROR.getMsg()+"msgId:"+msgId,
                        BlasterSysExceptionEnum.VERIFICATIONCODE_ERROR.getBizType());
            }
            //校验后,延迟三十秒
            redisUtil.expire(msgId,timeoutSecond);
        }
    }
}
